package cn.tb.org.controller;

import cn.tb.basic.anno.PreAuthorize;
import cn.tb.basic.util.AjaxResult;
import cn.tb.basic.util.PageList;
import cn.tb.org.domain.Department;
import cn.tb.org.query.DepartmentQuery;
import cn.tb.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询一条数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return departmentService.findById(id);
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    @PreAuthorize(name = "查看所有部门",value = "dept:findAll")
    public List<Department> queryAll(){
        return departmentService.findAll();
    }

    /**
     * 新增或者修改
     */
    @PutMapping
    public AjaxResult addOrUpt(@RequestBody Department department){
        try {
            if(department.getId() == null){
                //新增
                departmentService.save(department);
            }else{
                //修改
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("抱歉哦，系统错误，我们正在处理");
        }
    }

    /**
     * 高级查询+分页
     */
    @PostMapping
    @PreAuthorize(name = "部门高级查询分页",value = "dept:queryPage")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "删除一条部门数据",value = "dept:deleteById")
    public AjaxResult romave(@PathVariable Long id){
        try {
            departmentService.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("抱歉哦，系统错误，我们正在处理");
        }
    }

    /**
     * 批量删除
     */
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody Long[] ids){
        try {
            departmentService.patchRemove(ids);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("抱歉哦，系统错误，我们正在处理");
        }
    }

    /**
     * 无限级树
     * @return
     */
    @GetMapping("/tree")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }
}
